<template>
  <a href="#/home1" style="margin-right: 10px">home1</a>
  <a href="#/about1">about1</a>
  <div style="margin-bottom: 50px">{{ context1 }}</div>
  <!-- <div>
    <a href="/home2">122222222</a> 会向http://localhost:3000/home2这个地址发送请求
    <a href="/home2" @click.prevent="">33333</a> 有阻止默认事件不会发请求
  </div> -->
  <a
    href="/home2"
    style="margin-right: 10px"
    ref="home2"
    @click.prevent="handleHome"
    >home2</a
  >
  <a href="/about2" ref="about2" @click.prevent="handleAbout">about2</a>
  <div>{{ context2 }}</div>
</template>

<script setup>
//这章节了解下即可
import { ref, onBeforeUnmount } from "vue";
//hash原理
const context1 = ref("default1");
const hashchange = () => {
  debugger;
  switch (location.hash) {
    case "#/home1":
      context1.value = "home1";
      break;
    case "#/about1":
      context1.value = "about1";
      break;
    default:
      context1.value = "default1";
  }
};
window.addEventListener("hashchange", hashchange);

//history原理
const context2 = ref("/default2");
const home2 = ref(null);
const about2 = ref(null);
const handleHome = () => {
  //用replaceState就没有历史记录就不能退回或者退回到当前第一次打开的页面
  history.pushState({}, "", home2.value.getAttribute("href"));
  context2.value = home2.value.getAttribute("href");
};
const handleAbout = () => {
  //用replaceState就没有历史记录就不能退回或者退回到当前第一次打开的页面
  history.pushState({}, "", about2.value.getAttribute("href"));
  context2.value = about2.value.getAttribute("href");
};
const changeState = () => {
  switch (location.pathname) {
    case "/home2":
      context2.value = "/home2";
      break;
    case "/about2":
      context2.value = "/about2";
      break;
    default:
      context2.value = "/default2";
  }
};
window.addEventListener("popstate", changeState); //popstate事件在点击后退或前进按钮时触发，或者在JavaScript中调用history.back()、history.forward()、history.go()方法触发
onBeforeUnmount(() => {
  window.removeEventListener("hashchange", hashchange);
  window.removeEventListener("popstate", changeState);
});
</script>
